'use strict';
const Service = require('egg').Service;
const jwt = require('jsonwebtoken');
const { APPLICATION_STATUS } = require('../lib/status');

class ApplicationService extends Service {
  async token(code, salt) {
    const { app } = this;
    const identify = app.config.identify;
    const application = await app.model.Applications.findOne({
      attributes: { exclude: [ 'salt', 'updatedAt', 'createdAt' ] },
      where: { code, salt },
      raw: true,
    });
    if (!application) {
      return { errcode: app.ERRCODE.DATASET_ERROR, message: '应用Code或密钥错误' };
    }
    switch (application.status) {
      case APPLICATION_STATUS.CANCEL:
        return { errcode: app.ERRCODE.DATASET_ERROR, message: '该应用已作废！' };
      case APPLICATION_STATUS.NORMAL:
        await this.initVisitor(application.id);
        return {
          message: 'success',
          errcode: app.ERRCODE.NORMAL,
          data: Object.assign({}, application, {
            token: jwt.sign({ code: application.code,
              alias: `app/${application.code}`,
              code_id: application.id,
            }, identify.identification, {
              expiresIn: identify.expiresIn, // 过期时间
            }),
          }),
        };
      default:
        return { errcode: app.ERRCODE.DATASET_ERROR, message: '应用状态未知,请联系管理员！' };
    }
  }

  async initVisitor(code_id) {
    const urls = await this.app.model.ApplicationUrls.findAll({
      where: {
        application_id: code_id,
      },
    });
    await this.app.redis.del(`app-enabled-url:${code_id}`);
    for (const url of urls) {
      await this.app.redis.hset(`app-enabled-url:${code_id}`, url.url);
    }
  }

  async visitor(code_id, url) {
    if (await this.app.redis.hget(`app-enabled-url:${code_id}`, url)) {
      return true;
    }
    if (await this.app.redis.hget(`app-disabled-url:${code_id}`, url)) {
      return false;
    }
    return true;
  }
}

module.exports = ApplicationService;
